<template>
  <el-upload
    class="image-uploader"
    action
    :show-file-list="false"
    :http-request="handleImageUpload"
    :before-upload="beforeImageUpload"
  >
    <img
      v-if="imageUrl"
      :src="displayImageUrl"
      class="image"
    />
    <i
      v-else
      class="el-icon-plus image-uploader-icon"
    ></i>
    <div
      style="margin-top: 0px"
      slot="tip"
      class="el-upload__tip"
    >只能上传jpg/png文件，且不超过10M</div>
  </el-upload>
</template>

<script>
import { Message, Loading } from 'element-ui';
import { parseError } from '../utils';
import { v4 as uuid } from 'uuid';
import { uploadFileApi } from '../api/upload';
import { regularUrl } from '../utils/regular';

export default {
  model: {
    prop: 'imageUrl',
    event: 'update'
  },
  props: {
    imageUrl: {
      type: String,
      default: ''
    }
  },
  computed: {
    displayImageUrl() {
      /* eslint-disable */
      return regularUrl(this.imageUrl) ? this.imageUrl : `${process.env.VUE_APP_BASE_API.split('/').slice(0, 3).join('/')}/${this.imageUrl}`;
    }
  },
  methods: {
    handleImageUpload(option) {
      try {
        const [extension] = option.file.name.split('.').reverse();
        if (!extension) return Message.error('文件格式不正确');
        const loadingInstance = Loading.service({
          lock: true,
          text: '图片上传中，请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        const formData = new FormData();
        formData.append('file', option.file, encodeURIComponent(option.file.name));
        uploadFileApi(formData)
          .then(res => this.$emit('update', res))
          .catch(error => Message.error(parseError(error)))
          .finally(() => loadingInstance.close());
      } catch (error) {
        Message.error(parseError(error));
      }
    },
    beforeImageUpload(file) {
      const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJPGorPNG) Message.error('图片只能是JPG或PNG格式');

      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) Message.error('图片大小不能超过10MB');

      return isJPGorPNG && isLt10M;
    }
  }
};
</script>

<style lang="scss">
.image-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.image-uploader .el-upload:hover {
  border-color: #409eff;
}
.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.image {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
